#!/bin/ash

# test if we have input 3 num
if [ $# -ne 3 ]; then
	echo "useage:"
	echo "$0 gpio_pin_num max_temp min_temp"
	echo "example:"
	echo "$0 16 50 38"
	exit
fi

# readcputemp get the cpu temp from system
function readcputemp() {
	local temp=0
	cat /sys/class/thermal/thermal_zone0/temp | while read line
	do
		temp=$(expr $line / 1000)
		echo $temp
	done
}
# gpio pin 16 for control the cool cpu fan
PIN=$1
#PIN=16
# setupgpio make it for control rpi fan to cool the cpu
# export $PIN to /sys/class/gpio/gpio$PIN
function setupgpio() {
	echo $PIN > /sys/class/gpio/export
	echo out > /sys/class/gpio/gpio$PIN/direction
}

# unexport $PIN
function disablegpio() {
	echo $PIN > /sys/class/gpio/unexport
}


#max_temp > control the fan to turn on
#min_temp > control the fan to turn off
max_temp=$2
min_temp=$3
#rpifanctl
function rpifanctl() {
	if [ ! -d "/sys/class/gpio/gpio$PIN" ]; then
		setupgpio
	fi
	let cpu_temp=$(readcputemp)
	echo "cpu temp : $cpu_temp oC"
	if [ $cpu_temp -ge $max_temp ]; then
		echo 1 > /sys/class/gpio/gpio$PIN/value
	else if [ $cpu_temp -le $min_temp ]; then
		echo 0 > /sys/class/gpio/gpio$PIN/value
	else 
		echo $max_temp equal $min_temp
	fi	
	fi
}
	
rpifanctl $2 $3

